<?php

namespace app\admin\controller\purchase;

use app\common\controller\Backend;
use app\common\model\customer\Customer;
use app\common\model\data\Voucher;
use app\web\controller\Wweixin;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;
use app\admin\model\purchase\Requisition;
use app\common\model\Storehouse;
use app\common\model\purchase\Goods;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\goods\Goods as gGoods;
use app\common\model\purchase\Enter;
use app\common\model\supplier\Supplier;
use app\common\model\purchase\EnterGoods;
use function fast\e;
use think\Exception;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\purchase\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Order;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    public function index(){


        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $filter = $this->request->get("filter");
            $filter = (array)json_decode($filter, true);
            $where = [];
            if(session('admin')['storehouse_id'] >0){
                $where['o.storehouse_id'] =  session('admin')['storehouse_id'];
            }

            if(!empty($filter)){
                foreach ($filter as $key =>$value){
                    if($key == 'goods_name'){
                        $gids = Db::name('goods')->where(array('title'=>array('like','%'.$value.'%')))->field('id')->select();
                        $ids = [];
                        foreach ($gids as $v){
                           $ids[]= $v['id'];
                        }
                        if(!empty($ids)){
                            $orderids = Db::name('purchase_goods')->where(array('goods_id'=>array('in',$ids),'purchase_order_id'=>array('>',0)))->field('purchase_order_id')->select();
                            $oids = [];
                            foreach ($orderids as $v){
                                $oids[] = $v['purchase_order_id'];
                            }
                            if(!empty($oids)){
                                $where['o.id'] = array('in',$oids);
                            }
                        }
                    }
                    if($key == 'goods_number'){
                        $row = Db::name('goods')->where(array('number'=>$value))->find();
                        if(!empty($row)){
                            $orderids = Db::name('purchase_goods')->where(array('goods_id'=>$row['id'],'purchase_order_id'=>array('>',0)))->field('purchase_order_id')->select();
                            $oids = [];
                            foreach ($orderids as $v){
                                $oids[] = $v['purchase_order_id'];
                            }
                            if(!empty($oids)){
                                $where['o.id'] = array('in',$oids);
                            }
                        }
                    }
                    if($key == 'number'){
                        $where['o.number'] = array('like','%'.$value.'%');
                    }
                    if($key == 'operator'){
                        $where['o.operator'] = array('like','%'.$value.'%');
                    }
                    if($key == 'company'){
                        $where['o.company'] = array('like','%'.$value.'%');
                    }
                    if($key == 'order_price'){
                        $where['order_price'] = array('between',explode(',',$value));
                    }
                    if($key == 'status'){
                        $where['o.status'] = $value;
                    }
                    if($key == 'id'){
                        $where['o.id'] = $value;
                    }
                    if($key == 'name'){//仓库
                        $where2['name'] = $value;
                        $info = Storehouse::where($where2)->find();
                        $where['o.storehouse_id'] = $info['id'];
                    }
                    if($key == 'nickname'){
                        $where1['nickname'] = array('like','%'.$value.'%');
//                        exit;
                        $list =  Supplier::where($where1)->field('id')->select();
                        if(!empty($list)){
                            foreach ($list as $v){
                                $ids[] = $v['id'];
                            }
                            $where['o.supplier_id'] = array('in',$ids);
                        }

                    }
                    if($key == 'createtime'){
                        $arr = explode(' - ', $value);
                        $where['o.createtime'] = array('between time',$arr);
                    }
                }

            }
            $sort = input('sort');
            if($sort == 'id'){
                $sort = 'o.id';
            }
            if($sort == 'status'){
                $sort = 'o.status';
            }
            $order = input('order');
            $offset = input('offset');
            $limit = input('limit');

            $rows = Db::name('purchase_order')->alias('o')
                ->field('o.id,o.createtime,o.number,o.status,s.nickname,o.operator,o.company,order_goods_total,arrival_total,order_price,arrival_price,explain,abstract,tax,h.name')
//                ->join('admin a','o.admin_id = a.id')
                ->join('supplier s','o.supplier_id = s.id')
                ->join('storehouse h','o.storehouse_id = h.id')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $status = $this->model->order_status();
            foreach ($rows as $k=> $v){
                $rows[$k]['ystatus'] = $rows[$k]['status'];
                $rows[$k]['status'] = $status[$rows[$k]['status']];
//                $rows[$k]['arrival_total']=
            }

            $total = Db::name('purchase_order')->alias('o')
//                ->join('admin a','o.admin_id = a.id')
                ->join('supplier s','o.supplier_id = s.id')
                ->where($where)
//                ->order($sort, $order)
                ->count();
            return array('rows'=>$rows,'total'=>$total);
        }
        return $this->view->fetch();
    }
    public function add(){

        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        if ($this->request->isAjax()) {

            $num = $this->model->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $cdata = array(
//               'createtime'=>strtotime(input('createtime')),
               'supplier_id'=>input('supplier_id/d'),
               'tax'=>input('tax/s',0),
               'storehouse_id'=>input('storehouse_id/d',0),
               'explain'=>input('explain'),
//               'abstract'=>input('abstract'),
//               'discount'=>input('discount'),
//               'discount_explain'=>input('discount_explain'),
//               'actual_cost'=>input('actual_cost'),
               'number' =>'JD-T-'.date('Y-m-d').'-'.getnumber($num),
               'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
            );

            $params = input('');
            $gdata = $params['row'];

            //自检开始
            $order_goods_total = 0;
            $order_price = 0;
            foreach ($gdata as $v){
                //如果是运费 跳过
                if($v['goods_id'] == 1){
                    //统计
                    $v['fare'] = empty($v['fare'])?0:$v['fare'];
                    $order_goods_total += $v['goods_num'];
                    $order_price = $order_price + $v['ht_price']*$v['goods_num'] +$v['fare'];
                    continue;
                }
                $v['tax'] = empty($v['tax'])?0:$v['tax'];
                //检测数量状态是否发生变故
                $goods = new Goods();
                $ginfo = $goods->where(array('id'=>$v['goods_id']))->find();

                if($ginfo['status'] !=1){
                    $this->error('商品ID为'.$v['goods_id'].'的状态发生变化,请检查');
                }
                if($ginfo['goods_num'] != $v['goods_num']){
                    $this->error('商品ID为'.$v['goods_id'].'的商品数量发生变化,请检查');
                }
                if($ginfo['tax'] >13){
                    $this->error('商品ID为'.$v['goods_id'].'的税费异常,请检查');
                }
                //检测价格是否异常
                if(empty($v['unit_price'])){
                    $this->error('商品ID为'.$v['goods_id'].'价格不能为空,请检查');
                }
                //统计
                $v['fare'] = empty($v['fare'])?0:$v['fare'];
                $order_goods_total += $v['goods_num'];
                $order_price = $order_price + $v['ht_price']*$v['goods_num'] +$v['fare'];
            }
            $cdata['order_goods_total'] = $order_goods_total;
            $cdata['order_price'] = $order_price;

            Db::startTrans();
            try{
                $this->model->save($cdata);
                if(!$this->model->id){
                    Db::rollback();
                    throw new Exception('添加失败');
                }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>input('storehouse_id/d',0),
                    'bill_id'=>$this->model->id,
                    'type'=>1,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                foreach ($gdata as $k=>$v){
                    if($v['goods_id'] == 1){
                        $data = array(
                             'status'=>2,
                             'createtime'=>time(),
                             'needtime'=>time(),
                             'goods_id'=>1,
                             'goods_num'=>$v['goods_num'],
                             'purchase_order_id'=>$this->model->id,
                             'tax'=>0,
                             'storehouse_id'=>input('storehouse_id/d'),
                             'admin_id'=>session('admin')['id'],
                             'group_id'=>$group['group_id'],
                             'company'=>$group['name'],
                             'operator'=>session('admin')['nickname'],
                             'unit_price'=>$v['ht_price'],
                             'ht_price' => $v['ht_price'],
                        );

                        $goods = new Goods();
                        $res = $goods->save($data);
                        if(!$res){
                            Db::rollback();
                            throw new Exception('添加失败');
                        }
                        continue;
                    }
                    if($v['gid'] == 1){
                        $data = array(
                            'tax'=>0,
                            'unit_price'=>$v['ht_price'],
                            'ht_price' => $v['ht_price'],
                            'remark'=>$v['remark'],
                            'status'=>2,
                            'purchase_order_id'=>$this->model->id,
                        );

                        $goods = new Goods();
                        $res = $goods->save($data,array('id'=>$v['goods_id']));
                        if(!$res){
                            Db::rollback();
                            throw new Exception('添加失败');
                        }
                        continue;
                    }
                    $tax = empty($v['tax'])?0:$v['tax'];
                    $goods = new Goods();
                    $data = array(
                        'tax'=>$tax,
                        'unit_price'=>$v['unit_price'],
                        'ht_price' => $v['ht_price'],
                        'remark'=>$v['remark'],
                        'status'=>2,
                        'purchase_order_id'=>$this->model->id,
                    );
                    $res = $goods->save($data,array('id'=>$v['goods_id']));
                    if(!$res){
                        Db::rollback();
                        throw new Exception('添加失败');
                    }
                }
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'添加成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }

            exit;
        }

        $ids = input('ids');
        $supplier_id = input('supplier_id');

        $storehouse_id = input('storehouse_id');
        $supplier = new Supplier();
        $sinfo =  $supplier->where(array('id'=>$supplier_id))->find();
        $Storehouse = new Storehouse;
        $hrow = $Storehouse->find($storehouse_id);

        $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,number,g.storehouse_id,title,place_origin,specs,goods_num,unit,unit_price,tax,remark,a.nickname,g.purchase_order_id')
            ->alias('g')
            ->where(array('g.id'=>array('in',$ids)))
            ->join('goods go','g.goods_id = go.id')
            ->join('admin a','g.admin_id = a.id')
            ->select();

        foreach ($list as  $k=>$v){
               $GoodsHouseStock = new GoodsHouseStock;
               $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
               $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
        }

        $this->assign('list',$list);
        $this->assign('ids',$ids);
        $this->assign('sinfo',$sinfo);
        $this->assign('hrow',$hrow);
        $this->assign('nickname',session('admin')['nickname']);
        $this->assign('gname',$group['name']);
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function edit($ids = null){
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $tax = input('tax');
            $explain = input('explain');
            $params = input('row/a');
//            $actual_cost=input('actual_cost');
            Db::startTrans();
            try{
                $data = array(
//                     'actual_cost'=>$actual_cost,
                     'tax'=>$tax,
                     'explain'=>$explain,
                );
                $all_price = 0;
                foreach ($params as $v){
                    $gdata = array(
                        'unit_price'=>$v['unit_price'],
                        'tax'=>$v['tax'],
                        'ht_price' => $v['ht_price'],
                        'remark'=>$v['remark'],
                    );
                    $all_price+=$v['ht_price']*$v['goods_num'];
                    $gGoods = new Goods;
                    $gGoods->save($gdata,array('id'=>$v['goods_id']));
                }
                if(empty($all_price)){
                    throw new Exception('金额异常');
                }
                $data['order_price'] = $all_price;
                $this->model->save($data,array('id'=>$ids));
                Db::commit();
                return  array(
                  'code'=>1,
                  'msg'=>'修改成功'
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


        $Storehouse = new Storehouse;
        $Supplier = new Supplier;
        $srow = $Supplier->where(array('id'=>$row['supplier_id']))->find();

        $hrow = $Storehouse->where(array('id'=>$row['storehouse_id']))->find();
        $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,g.storehouse_id,number,title,place_origin,specs,goods_num,unit,unit_price,ht_price,tax,remark,fare,cost,a.nickname')
            ->alias('g')
            ->where(array('g.purchase_order_id'=>$ids))
            ->join('admin a','g.admin_id = a.id')
            ->join('goods go','g.goods_id = go.id')
            ->select();
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
        }
        $this->assign('snick',isset($srow['nickname'])?$srow['nickname']:'');
        $this->assign('hname',isset($hrow['name'])?$hrow['name']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
//    public function choose(){
//        return $this->view->fetch();
//    }
    public function getgetrequisition($ids = null){
        $ids = explode(',',input('ids'));
        $list = Db::name('purchase_goods')
            ->field('g.id,number,title,place_origin,specs,goods_num,unit,unit_price,tax,remark')
            ->alias('g')
            ->where(array('g.id'=>array('in',$ids)))
            ->join('goods go','g.goods_id = go.id')
            ->select();
        if(empty($list)){
            return null;
        }
        return $list;
    }
    public function detail($ids = null){
        $row = $this->model->find($ids);
        $Storehouse = new Storehouse;
        $Supplier = new Supplier;
        $srow = $Supplier->where(array('id'=>$row['supplier_id']))->find();

        $hrow = $Storehouse->where(array('id'=>$row['storehouse_id']))->find();
        $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,g.storehouse_id,number,title,place_origin,specs,goods_num,unit,unit_price,tax,remark,fare,cost,ht_price')
            ->alias('g')
            ->where(array('g.purchase_order_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->select();
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $this->assign('snick',isset($srow['nickname'])?$srow['nickname']:'');
        $this->assign('hname',isset($hrow['name'])?$hrow['name']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    //入库
    public function enter($ids = null){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        $row = $this->model->find($ids);
        if ($this->request->isAjax()) {

            $thumb = input('thumb');
            if(empty(trim($thumb))){
                $this->error('入库凭证不能为空');
            }

            if(empty($row) ){
                $this->error('采购订单状态异常,请检查');
            }

            $num = Db::name('purchase_enter')->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $params = input();
            if(empty($params['actual_cost'])){
                $this->error('金额异常');
            }
            $edata = array(
                'purchase_order_id'=>$ids,
//                'createtime'=>strtotime(input('createtime')),
                'paytime'=>strtotime(input('paytime')),
                'explain'=>input('explain'),
//                'abstract'=>input('abstract'),
                'number'=>'JK-T-'.date('Y-m-d').'-'.getnumber($num),
                'admin_id'=>session('admin')['id'],
                'group_id'=>$group['group_id'],
                'company'=>$group['name'],
                'operator'=>session('admin')['nickname'],
                'storehouse_id'=>$row['storehouse_id'],
                'supplier_id'=>$row['supplier_id'],
                'goods_cost'=>$params['goods_cost'],
                'discount'=>$params['discount'],
                'discount_explain'=>$params['discount_explain'],
                'actual_cost'=>$params['actual_cost'],
                'allfare'=>$params['allfare'],
                'tax'=>$row['tax'],
            );

            $gdata = $params['row'];

            Db::startTrans();
            try{
                    $Enter = new Enter();
                    $Enter->save($edata);
                    if(!$Enter->id){
                        Db::rollback();
                        throw new Exception('添加失败');
                    }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$row['storehouse_id'],
                    'bill_id'=>$Enter->id,
                    'type'=>2,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                    $Voucher = new Voucher;
                    $Voucher->save(array(
                        'image'=>$thumb,
                        'type'=>2,
                        'source_id'=>$Enter->id,
                        'is_go'=>2,
                    ));



                    $ogdata = [];

                    $runum = 0;
                    $rprice = 0;
                    foreach ($gdata as $v){

                        if(empty($v['goods_num'])){
                            continue;
                        }
                        //数据对比
                        $goods = new Goods();
                        $ginfo = $goods->where(array('id'=>$v['purchase_goods_id']))->find();
                        //剩余可入库数量 = 采购数量-已入库数量
                        $EnterGoods = new EnterGoods;
                        $egoodcont = $EnterGoods->where(array('purchase_order_id'=>$ids,'purchase_goods_id'=>$v['purchase_goods_id'],'goods_id'=>$v['goods_id'],'status'=>array('>',0)))->sum('goods_num');
                        if($v['goods_num'] >$ginfo['goods_num'] - $egoodcont){
                            Db::rollback();
                            throw new Exception('商品'.$v['purchase_goods_id'].'数量超过采购数量,目前入库'.$egoodcont);
                        }else{
                            //相等的情况下 全部入库了
                           if($v['goods_num'] == $ginfo['goods_num'] - $egoodcont){
                                $goods = new Goods();
                                $goods->save(array('status'=>4),array('id'=>$v['purchase_goods_id']));
                           }else{
                               $goods = new Goods();
                               $goods->save(array('status'=>3),array('id'=>$v['purchase_goods_id']));
                           }
                        }
                        //存储记录
                        $ogdata[] = array(
                          'purchase_order_id'=>$ids,
                          'goods_id'=>$ginfo['goods_id'],
                          'goods_num'=>$v['goods_num'],
                          'unit_price'=>$ginfo['unit_price'],
                          'ht_price'=>$ginfo['ht_price'],
                          'tax'=>$ginfo['tax'],
//                          'fare'=>$ginfo['fare'],
                          'cost_price'=>$ginfo['unit_price'],
                          'remark'=>$v['remark'],
                          'purchase_enter_id'=>$Enter->id,
                          'purchase_goods_id'=>$v['purchase_goods_id'],
                            'storehouse_id'=>$row['storehouse_id'],
                        );
                        $runum +=$v['goods_num'];
                        $rprice +=$v['goods_num']*$ginfo['ht_price'];
                    }

                    $EnterGoods = new EnterGoods;
                    $EnterGoods->saveAll($ogdata);

                    //判断采购单是否完成
                    $goods = new Goods();
                    $gnum = $goods->where(array('purchase_order_id'=>$ids))->count();
                    $goods = new Goods();
                    $succnum = $goods->where(array('purchase_order_id'=>$ids,'status'=>4))->count();

                    if($gnum == $succnum){
                        $this->model->save(array(
                            'status'=>4,
                            'arrival_price'=>$row['arrival_price']+$rprice,
                            'arrival_total'=>$row['arrival_total']+$runum,
                        ),array('id'=>$ids));
                    }else{
                        $this->model->save(array(
                            'status'=>3,
                            'arrival_price'=>$row['arrival_price']+$rprice,
                            'arrival_total'=>$row['arrival_total']+$runum,
                        ),array('id'=>$ids));
                    }

                $wx = new Wweixin;
                $wx->senmsg(2);
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'入库成功',
                    );
            }catch (\Exception $e) {
//                dump($e);
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $goods = new Goods();
        $glist = $goods->where(array('purchase_order_id'=>$ids))->select();
        $ids = [];
        foreach ($glist as $v){
            $ids[] = $v['id'];
        }

        $list = Db::name('purchase_goods')
            ->field('g.id,goods_id,g.storehouse_id,number,title,place_origin,specs,goods_num,unit,unit_price,ht_price,tax,remark,fare,cost')
            ->alias('g')
            ->where(array('g.id'=>array('in',$ids)))
            ->join('goods go','g.goods_id = go.id')
            ->select();

        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $enterGood = new EnterGoods();
            $list[$k]['enter_num'] = $enterGood->where(array('purchase_order_id'=>$row['id'],'purchase_goods_id'=>$v['id'],'status'=>array('>',0)))->sum('goods_num');
        }





        $supplier_id = $row['supplier_id'];
        $supplier = new Supplier();
        $sinfo =  $supplier->where(array('id'=>$supplier_id))->find();
        $Storehouse = new Storehouse();
        $hinfo =  $Storehouse->where(array('id'=>$row['storehouse_id']))->find();
        $this->assign('nickname',session('admin')['nickname']);
        $this->assign('gname',$group['name']);
        $this->assign('sinfo',$sinfo);
        $this->assign('hinfo',$hinfo);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('ids',implode(',',$ids));
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    //采购单审核
    public function examine($ids = null){

        $status = input('status/d',0);
        if(empty($status)){
            $this->error('状态异常');
        }
        $row = $this->model->find($ids);
        if(!$row){
            $this->error('订单不存在');
        }
        if($row['status'] !=1){
            $this->error('订单状态异常');
        }

        Db::startTrans();
        try {
            $odata['status'] = $status;
            if ($status == 2) {
                $type = 1;
                $custrow = Supplier::find($row['supplier_id']);
                $ress = Db::name('analysis')->insert(array(
                    'is_income' => 2,
                    'source' => 1,
                    'cost' => $row['order_price'],
                    'admin_id'=>$row['admin_id'],
                    'group_id'=>$row['group_id'],
                    'company'=>$row['company'],
                    'operator'=>$row['operator'],
                    'source_id' => $ids,
                    'obj_id' => $row['supplier_id'],
                    'storehouse_id' => $row['storehouse_id'],
//                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/order',
                    'settle_name' => $custrow['nickname'],
                    'number' => $row['number'],
                    'createtime' => time(),
                    'explain'=>$row['explain'],//摘要
                ));
                if (!$ress) {
                    throw new Exception('数据异常');
                }
            }
            if ($status == 5) {
//                $Goods = new Goods;
//                $Goods->save(array('status' => 5), array('purchase_order_id' => $ids));
                $type = 2;
                $list = Db::name('purchase_goods')->where(array('purchase_order_id'=>$ids))->select();
                foreach ($list as $v){
                    //重置请购状态数据
                    Db::name('purchase_goods')->where(array('id'=>$v['id']))->update(array('status'=>1,'purchase_order_id'=>0,'unit_price'=>0,'ht_price'=>0));
                }
            }
            Db::name('examine_log')->insert(array(
               'admin_id'=>session('admin')['id'],
                'type'=>$type,
                'createtime'=>time(),
                'controller'=>'purchase/order',
                'source_id'=>$ids,
                'source'=>1,
                'remark'=>'采购单',
                'number'=>$row['number'],
            ));
            $res = $this->model->save($odata, array('id' => $ids));
            if($res){
                Db::commit();
                return  array(
                    'code'=>1,
                    'msg'=>'审核成功',
                );
            }
//        $sql = Db::table('zax_purchase_order')->getLastSql();
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->error('审核失败');
    }
    public function getfreight(){
        $gGoods = new gGoods;
        $row =$gGoods->where(array('id'=>1))->find();
        $this->success('请求成功','',$row);
    }
    public function printing($ids = null){
        $row = $this->model->find($ids);
        $Storehouse = new Storehouse;
        $Supplier = new Supplier;
        $srow = $Supplier->where(array('id'=>$row['supplier_id']))->find();

        $hrow = $Storehouse->where(array('id'=>$row['storehouse_id']))->find();
        $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,g.storehouse_id,number,title,place_origin,specs,goods_num,unit,unit_price,tax,remark,fare,cost,ht_price')
            ->alias('g')
            ->where(array('g.purchase_order_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->select();
        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['buy_price'] = round($v['goods_num']*($v['ht_price']/((100+$v['tax'])/100)),2);
            $list[$k]['tax_all'] = round(($v['ht_price']/($v['tax']+100))*$v['tax']*$v['goods_num'],2);
        }
        $this->assign('snick',isset($srow['nickname'])?$srow['nickname']:'');
        $this->assign('hname',isset($hrow['name'])?$hrow['name']:'');
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
    public function import($ids = null){
        $row = Db::name('purchase_order')
            ->alias('p')
            ->join('supplier s','p.supplier_id = s.id')
            ->where(array('p.id'=>$ids))
            ->find();

        $rows = $list = Db::name('purchase_goods')
            ->field('g.id,g.goods_id,g.storehouse_id,go.number,title,place_origin,specs,goods_num,unit,unit_price,tax,g.remark,fare,cost,ht_price,s.name')
            ->alias('g')
            ->where(array('g.purchase_order_id'=>$ids))
            ->join('goods go','g.goods_id = go.id')
            ->join('storehouse s','g.storehouse_id = s.id')
            ->select();
//        dump($rows);
//        exit;


//        $template_path = '/www/wwwroot/erp.gotobby.com/public/template/demo.xls';
//        $spreadsheet = IOFactory::load($template_path);
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('采购订单');
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow( 1, 1, '采购订单');


        $worksheet->setCellValueByColumnAndRow( 1, 2, '制单人');
        $worksheet->setCellValueByColumnAndRow( 6, 2, $row['operator']);
        $worksheet->setCellValueByColumnAndRow( 11,2, '税率(%)');
        $worksheet->setCellValueByColumnAndRow( 16,2, $row['tax']);

        $worksheet->setCellValueByColumnAndRow( 1, 3, '预设进价选择');
        $worksheet->setCellValueByColumnAndRow( 6, 3, '');
        $worksheet->setCellValueByColumnAndRow( 11,3, '录单日期');
        $worksheet->setCellValueByColumnAndRow( 16,3, date('Y-m-d',$row['createtime']));

        $worksheet->setCellValueByColumnAndRow( 1, 4, '单据编号');
        $worksheet->setCellValueByColumnAndRow( 6, 4, $row['number']);
        $worksheet->setCellValueByColumnAndRow( 11,4, '往来单位');
        $worksheet->setCellValueByColumnAndRow( 16,4, $row['nickname']);

        $worksheet->setCellValueByColumnAndRow( 1, 5, '结算单位');
        $worksheet->setCellValueByColumnAndRow( 6, 5, $row['nickname']);
        $worksheet->setCellValueByColumnAndRow( 11,5, '经手人');
        $worksheet->setCellValueByColumnAndRow( 16,5, $row['operator']);

        $worksheet->setCellValueByColumnAndRow( 1, 6, '部门');
        $worksheet->setCellValueByColumnAndRow( 6, 6, $row['company']);
        $worksheet->setCellValueByColumnAndRow( 11,6, '入库仓库');
        $worksheet->setCellValueByColumnAndRow( 16,6, $rows[0]['name']);

//        $worksheet->setCellValueByColumnAndRow( 1,6, '到货时间');
//        $worksheet->setCellValueByColumnAndRow( 2,6, '');
//        $worksheet->setCellValueByColumnAndRow( 3,6, '说明');
//        $worksheet->setCellValueByColumnAndRow( 4,6, '0');

        $worksheet->setCellValueByColumnAndRow( 1,7, '说明');
        $worksheet->setCellValueByColumnAndRow( 2,7, $row['explain']);
        $worksheet->setCellValueByColumnAndRow( 3,7, '');
        $worksheet->setCellValueByColumnAndRow( 4,7, '');

        //合并单元格
        $worksheet->mergeCells('A1:T1');

        //设置高度
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(10);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(15);

        $worksheet->mergeCells('A2:E2');
        $worksheet->mergeCells('F2:j2');
        $worksheet->mergeCells('K2:O2');
        $worksheet->mergeCells('P2:T2');

        $worksheet->mergeCells('A3:E3');
        $worksheet->mergeCells('F3:j3');
        $worksheet->mergeCells('K3:O3');
        $worksheet->mergeCells('P3:T3');

        $worksheet->mergeCells('A4:E4');
        $worksheet->mergeCells('F4:j4');
        $worksheet->mergeCells('K4:O4');
        $worksheet->mergeCells('P4:T4');

        $worksheet->mergeCells('A5:E5');
        $worksheet->mergeCells('F5:j5');
        $worksheet->mergeCells('K5:O5');
        $worksheet->mergeCells('P5:T5');

        $worksheet->mergeCells('A6:E6');
        $worksheet->mergeCells('F6:j6');
        $worksheet->mergeCells('K6:O6');
        $worksheet->mergeCells('P6:T6');

        $worksheet->mergeCells('A7:E7');
        $worksheet->mergeCells('F7:j7');
        $worksheet->mergeCells('K7:O7');
        $worksheet->mergeCells('P7:T7');

        $worksheet->setCellValueByColumnAndRow(1,  9, '行号');
        $worksheet->setCellValueByColumnAndRow(2,  9, '入库仓库');
        $worksheet->setCellValueByColumnAndRow(3,  9, '商品编号');
        $worksheet->setCellValueByColumnAndRow(4,  9, '商品名称');
        $worksheet->setCellValueByColumnAndRow(5,  9, '规格');
        $worksheet->setCellValueByColumnAndRow(6,  9, '产地');
        $worksheet->setCellValueByColumnAndRow(7,  9, '账面库存');
        $worksheet->setCellValueByColumnAndRow(8,  9, '采购单位');
        $worksheet->setCellValueByColumnAndRow(9,  9, '采购数量');
        $worksheet->setCellValueByColumnAndRow(10, 9, '采购单价');
        $worksheet->setCellValueByColumnAndRow(11, 9, '采购金额');
        $worksheet->setCellValueByColumnAndRow(12, 9, '税率(%)');
        $worksheet->setCellValueByColumnAndRow(13, 9, '含税单价');
        $worksheet->setCellValueByColumnAndRow(14, 9, '税额');
        $worksheet->setCellValueByColumnAndRow(15, 9, '价税合计');
        $worksheet->setCellValueByColumnAndRow(16, 9, '已收货数量');
        $worksheet->setCellValueByColumnAndRow(17, 9, '状态');
        $worksheet->setCellValueByColumnAndRow(18, 9, '备注');

        $len = count($rows);
        for ($i=0; $i < $len; $i++) {

            $j = $i + 10;
//            $spreadsheet->getActiveSheet()->getColumnDimension($j)->setAutoSize(true);
            $house = new GoodsHouseStock();
            $stock = $house->getstock($rows[$i]['goods_id'],$rows[$i]['storehouse_id']);
            //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $i+1);
            $worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['name']);

            $worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['number']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['title']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['specs']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $rows[$i]['place_origin']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $stock);
            $worksheet->setCellValueByColumnAndRow(8, $j, $rows[$i]['unit']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $rows[$i]['goods_num']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $rows[$i]['unit_price']);
            $worksheet->setCellValueByColumnAndRow(11, $j, $rows[$i]['unit_price']*$rows[$i]['goods_num']);
            $worksheet->setCellValueByColumnAndRow(12, $j, $rows[$i]['tax']);
            $worksheet->setCellValueByColumnAndRow(13, $j, $rows[$i]['ht_price']);
            $worksheet->setCellValueByColumnAndRow(14, $j, $rows[$i]['tax']*$rows[$i]['goods_num']);
            $worksheet->setCellValueByColumnAndRow(15, $j, $rows[$i]['ht_price']*$rows[$i]['goods_num']);
            $worksheet->setCellValueByColumnAndRow(16, $j, 0);
            $worksheet->setCellValueByColumnAndRow(17, $j, '');
            $worksheet->setCellValueByColumnAndRow(18, $j, $rows[$i]['remark']);
        }

        $filename = '采购单.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$filename.'"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }
    public function cancelbill($ids=null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);
        if($row['status'] !=2){
            $this->error('状态异常');
        }
        $analysis = Db::name('analysis')->where(array(
            'source'=>1,
            'source_id' => $row['id'],
            'storehouse_id' => $row['storehouse_id'],
        ))->find();
        //只有财务数据在待处理的时候 才能处理
        if($analysis['status'] != 1){
            $this->error('财务状态异常,请处理');
        }


        //防止意外 再检测一次入库单
        $enter = new Enter();
        $count = $enter->where(array('status'=>array('<',3),'purchase_order_id'=>$ids))->count();
        if($count >0){
            $this->error('单据下还有入库单未处理');
        }
        Db::startTrans();
        try {

            $this->model->save(array('status'=>6),array('id'=>$ids));
            $list = Db::name('purchase_goods')->where(array('purchase_order_id'=>$ids))->select();
            foreach ($list as $v){
                //重置请购状态数据
                Db::name('purchase_goods')->where(array('id'=>$v['id']))->update(array('status'=>1,'purchase_order_id'=>0,'unit_price'=>0,'ht_price'=>0));
            }

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

            Db::name('cancel_bill')
                ->insert(array(
                    'reason' => $reason,
                    'source' => 1,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/order',
                    'source_id' => $row['id'],
                    'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/order',
                'source_id'=>$ids,
                'source'=>1,
                'remark'=>'采购入库单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            //中止财务记录
            $ress = Db::name('analysis')->where(array(
                'id' => $analysis['id']
            ))->update(array('status' => 4));
            if (!$ress) {
                throw new Exception('数据异常');
            }
            Db::commit();
            return array(
                'code' => 1,
                'msg' => '成功'
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }


    }
    //强制完结订单
    public function forceend($ids){
        $row = $this->model->find($ids);
        if($row['status'] !=3){
            $this->error('状态异常');
        }
        if($this->request->isAjax()){
            $arow = Db::name('analysis')->where(array(
                'is_income' => 2,
                'source' => 1,
                'source_id' => $ids,
                'storehouse_id' => $row['storehouse_id'],
            ))->find();
            if($arow['status'] != 1){
                $this->error('财务状态异常');
            }

            Db::startTrans();
            try{

                //修改连带订单和请购信息
//                $enter_price = Db::name('purchase_enter')->where(array('purchase_order_id'=>$ids))->sum('goods_cost');
//            $list = Db::name()
                $glist = Db::name('purchase_enter_goods')->where(array('purchase_order_id'=>$ids))->select();
                $gids= [];

                $p_num = 0; //采购数量
                $p_price  = 0; //采购金额
                foreach ($glist as $v){
                    $p_num+=$v['goods_num'];
                    $p_price+=$v['goods_num']*$v['ht_price'];
                    if(isset($gids[$v['goods_id']])){
                        $gids[$v['goods_id']] += $v['goods_num'];
                    }else{
                        $gids[$v['goods_id']] = $v['goods_num'];
                    }
                }
                $data['status'] = 4;
                $data['order_price'] = $p_price;
                $data['order_goods_total'] = $p_num;
                //修改该订单状态为入库完成
                $this->model->save($data,array('id'=>$ids));
                //修改请购信息 -------------------这个可选
                foreach ($gids as $k=> $v){
                    Db::name('purchase_goods')->where(array('goods_id'=>$k,'purchase_order_id'=>$ids))->update(array('goods_num'=>$v));
                }
                //修改财务信息
                Db::name('analysis')->where(array(
                    'id'=>$arow['id']
                ))->update(array(
                    'cost' => $p_price,
                ));
                Db::commit();
                return array(
                  'code'=>1,
                  'msg'=>'完结成功'
                );

            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
        $goods = new Goods();
        $glist = $goods->where(array('purchase_order_id'=>$ids))->select();
        $ids = [];
        foreach ($glist as $v){
            $ids[] = $v['id'];
        }

        $list = Db::name('purchase_goods')
            ->field('g.id,goods_id,g.storehouse_id,number,title,place_origin,specs,goods_num,unit,unit_price,ht_price,tax,remark,fare,cost')
            ->alias('g')
            ->where(array('g.id'=>array('in',$ids)))
            ->join('goods go','g.goods_id = go.id')
            ->select();

        foreach ($list as  $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $list[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],$v['storehouse_id']);
            $list[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],$v['storehouse_id']);
            $enterGood = new EnterGoods();
            $list[$k]['enter_num'] = $enterGood->where(array('purchase_order_id'=>$row['id'],'purchase_goods_id'=>$v['id'],'status'=>array('>',0)))->sum('goods_num');
        }





        $supplier_id = $row['supplier_id'];
        $supplier = new Supplier();
        $sinfo =  $supplier->where(array('id'=>$supplier_id))->find();
        $Storehouse = new Storehouse();
        $hinfo =  $Storehouse->where(array('id'=>$row['storehouse_id']))->find();
        $this->assign('nickname',session('admin')['nickname']);
        $this->assign('gname',$group['name']);
        $this->assign('sinfo',$sinfo);
        $this->assign('hinfo',$hinfo);
        $this->assign('list',$list);
        $this->assign('row',$row);
        $this->assign('ids',implode(',',$ids));
        $arr = explode('/',$_SERVER['REQUEST_URI']);
        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }

}
